package com.yc.web.EchoServer;

import com.yc.commons.RedisHelper;

import com.yc.model.JsonModel;
import com.yc.web.servlets.BaseServlet;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author SLGRoutine
 * @date 2024/7/5
 */
@WebServlet("/admin/adminchat.action")
public class AdminChatServlet extends BaseServlet {

    /**
     * 获取通知后，刷新数据
     *
     * @param req
     * @param resp
     */
    public void responseNotice(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JsonModel jm = new JsonModel();
        Jedis jedis = RedisHelper.getRedisInstance();


        String uid = req.getParameter("uid");
        System.out.println(uid);

//        回传给前端的聊天内容
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 获取有序集合的全部成员
        Set<Tuple> sortedSetMembers = jedis.zrangeWithScores("content_" + uid, 0, -1);
        // 打印输出每个成员及其分数
        for (Tuple member : sortedSetMembers) {
            String memberValue = member.getElement(); // 内容
            String timeForDat = getDateFormat((long) member.getScore());
            Map<String, Object> map = new HashMap<>();
            map.put("time", timeForDat);
            map.put("content", memberValue);
            returnList.add(map);
        }
        jm.setCode(1);
        jm.setObj(returnList);
        super.writeJson(jm, resp);

    }


    /**
     * 获取websocket初始化请求参数，并传递给前端
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void getServerInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> serverInfo = new HashMap<>();
        String protocol = request.isSecure() ? "wss" : "ws";
        String host = request.getServerName();
        int port = request.getServerPort();
        String contextPath = request.getContextPath();

        serverInfo.put("protocol", protocol);
        serverInfo.put("host", host);
        serverInfo.put("port", String.valueOf(port));
        serverInfo.put("contextPath", contextPath);

        JsonModel jm = new JsonModel();
        jm.setCode(1);//成功
        jm.setObj(serverInfo);
        writeJson(jm, response);
    }

    /**
     * 向客户发送信息，并发送通知
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void setMassage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JsonModel jm = new JsonModel();
//        获取前端数据
        String content = req.getParameter("content");//客服发的内容
        String uid = req.getParameter("uid");//发送的用户对象
        System.out.println("当前发送对象：" + uid);
        System.out.println("当前发送内容：" + content);
        Jedis jedis = RedisHelper.getRedisInstance();
        //        发通知给客户
        AdminEchoServer adminEchoServer = new AdminEchoServer();
        adminEchoServer.send("admin");
        // 当前时间戳
        long currentTimestamp = System.currentTimeMillis() / 1000;
//        向数据库添加当前用户信息
        jedis.zadd("content_" + uid, currentTimestamp, "admin:" + content);

//        回传给前端的聊天内容
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 获取有序集合的全部成员
        Set<Tuple> sortedSetMembers = jedis.zrangeWithScores("content_" + uid, 0, -1);
        // 打印输出每个成员及其分数
        for (Tuple member : sortedSetMembers) {
            String memberValue = member.getElement(); // 内容
            String timeForDat = getDateFormat((long) member.getScore());
            Map<String, Object> map = new HashMap<>();
            map.put("time", timeForDat);
            map.put("content", memberValue);
            returnList.add(map);
        }
        //获取更新的数据，回传给前端
        jm.setCode(1);
        jm.setObj(returnList);
        super.writeJson(jm, resp);
    }

    /**
     * 初始化聊天数据数据
     *
     * @param req
     * @param resp
     */
    public void initChatContent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JsonModel jm = new JsonModel();
        Jedis jedis = RedisHelper.getRedisInstance();

        /**
         * 这两项是回传的消息内容
         */
//      回传的用户ID列表
        List<Integer> users = new ArrayList<>();
//      每个用户对应的消息内容
        List<List<Map<String, Object>>> messages = new ArrayList<>();

        // 获取所有以 "content_" 开头的键名
        Set<String> keys = jedis.keys("content_*");
//        循环每一个集合
        for (String key : keys) {
//            获取当前用户的的消息集合
            Set<Tuple> sortedSetMembers = jedis.zrangeWithScores(key, 0, -1);
            System.out.println("当前集合为---" + key);         //content_2
//            获取ID存到用户列表
            String[] parts = key.split("_");
            Integer userId = Integer.valueOf((parts[1]));

            users.add(userId);

            List<Map<String, Object>> list = new ArrayList<>();
            // 获取每个集合的内容
            for (Tuple member : sortedSetMembers) {
                String chatContent = member.getElement(); // 内容  admin:你好
                String timeFormat = getDateFormat((long) member.getScore());//将时间蹉转换为日期格式的时间
                System.out.println(chatContent);
                System.out.println(timeFormat);

                Map<String, Object> map = new HashMap<>();
                map.put("time", timeFormat);
                map.put("content", chatContent);
                list.add(map);
            }
            messages.add(list);
        }

        System.out.println(users);
        System.out.println(messages);

        List resultList = new ArrayList();
        resultList.add(users);
        resultList.add(messages);

        jm.setCode(1);
        jm.setObj(resultList);
        super.writeJson(jm, resp);
    }


    /**
     * 将时间撮转换为日期格式事件
     *
     * @param score
     * @return
     */
    public static String getDateFormat(Long score) {
        // 创建 Date 对象并设置时间戳（需要乘以1000转换为毫秒）
        Date date = new Date(score * 1000L);

        // 创建 SimpleDateFormat 对象，定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 使用 SimpleDateFormat 格式化 Date 对象
        String formattedDate = sdf.format(date);
        return formattedDate;
    }
}
